import {reactive, watch} from "vue";
import type {ITaskItem} from "@/Types/ITaskItem";
import type {ITodoListService} from "@/Types/ITodoListService";

export class TodoListService implements ITodoListService{
    #list:ITaskItem[] = []; //在js中 以#开头的，是私有的

    constructor() {
        this.#list = reactive(this.loadFromLocalStorage())
        watch(this.#list,()=>{ //做一个侦听
          this.saveToLocalStorage();
          console.log("list被修改");
        })

    }
    addNewTask(taskContent: string): boolean {
        const newTask = {content: taskContent, isDone:false };
        this.#list.push(newTask);

        return true;
    }

    deleteTask(taskIndex: number): boolean {
        this.#list.splice(taskIndex, 1);
        return true;
    }

    getList(): ITaskItem[] {
        return this.#list; //在ts中必须加上this
    }

    loadFromLocalStorage(): ITaskItem[] {
        let stringInStorage = localStorage.getItem('list')??'[]';//条件判断，给一个空值
        return JSON.parse(stringInStorage);
    }

    saveToLocalStorage(): boolean {
        localStorage.setItem("list",JSON.stringify(this.#list))
        return true;
    }

}